<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <!-- <script src="https://code.jquery.com/jquery-1.11.1.js"></script> -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

    <style>
      .msg {
        width: 90%;
        min-height: 400px;
        margin: 0 auto;
        background-color: #fefefe;
        overflow: hidden;
      }
      .other {
        text-align: left;
      }
      .mine {
        text-align: right;
      }
      .other span {
        background-color: red;
        padding: 0 10px;
        border-radius: 5px;
      }
      .mine span {
        background-color: orange;
        padding: 0 10px;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <input type="text" class="info" />
    <button class="send">发送</button>
    <div class="msg">
      <p class="other">
        <span>hello</span>
      </p>
      <p class="mine">
        <span>hi</span>
      </p>
    </div>
    <!-- 消息和发送者还需要缓存在本地 -->
    <script>
      // let socket = io();
      let socket = io.connect("http://192.168.124.166:3030");
      let value;
      const userId = Math.floor(Math.random() * 100);
      $(".send").click(function () {
        value = $(".info").val();
        // 发送时携带用户ID

        socket.emit("chat", { userId, value });
        $(".info").val("");
        $(".msg").append(`<p class="mine"><span>${value}</span></p>`);
      });

      socket.on("chat", (msg) => {
        // 收到信息
        // 判定是不是自己
        // console.log(msg);
        if (msg.userId !== userId) {
          $(".msg").append(`<p class="other"><span>${msg.value}</span></p>`);
        }
      });
    </script>
  </body>
</html>
